<template>
  <div class="news-detail">
    <!-- 头部导航 -->
    <header class="header">
      <div class="container">
        <div class="header-content">
          <div class="logo" @click="goHome">
            <h1>新闻平台</h1>
          </div>
          <div class="nav-actions">
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="main" v-loading="loading">
      <div class="container">
        <div class="content" v-if="newsDetail">
          <!-- 新闻内容 -->
          <article class="article">
            <header class="article-header">
              <h1 class="article-title">{{ newsDetail.title }}</h1>
              
              <div class="article-meta">
                <div class="meta-left">
                  <span class="publish-time">{{ formatTime(newsDetail.publishTime) }}</span>
                  <span class="category" v-if="newsDetail.categoryName">{{ newsDetail.categoryName }}</span>
                </div>
                
                <div class="meta-right">
                  <span class="views">
                    <el-icon><View /></el-icon>
                    {{ newsDetail.viewCount }} 阅读
                  </span>
                  <span class="likes">
                    <el-icon><Star /></el-icon>
                    {{ newsDetail.likeCount }} 点赞
                  </span>
                </div>
              </div>
            </header>
            
            <!-- 封面图片 -->
            <div class="article-cover" v-if="newsDetail.coverImage">
              <img :src="newsDetail.coverImage" :alt="newsDetail.title" />
            </div>
            
            <!-- 摘要 -->
            <div class="article-summary" v-if="newsDetail.summary">
              <p>{{ newsDetail.summary }}</p>
            </div>
            
            <!-- 正文内容 -->
            <div class="article-content" v-html="newsDetail.content"></div>
            
            <!-- 文章底部操作 -->
            <footer class="article-footer">
              <div class="article-actions">
                <el-button 
                  type="primary" 
                  :icon="liked ? 'StarFilled' : 'Star'"
                  @click="handleLike"
                  :loading="liking"
                >
                  {{ liked ? '已点赞' : '点赞' }} ({{ newsDetail.likeCount }})
                </el-button>
                
                <el-button @click="handleShare">
                  <el-icon><Share /></el-icon>
                  分享
                </el-button>
              </div>
            </footer>
          </article>
          
          <!-- 相关推荐 -->
          <section class="related-news" v-if="relatedNews.length > 0">
            <h3 class="section-title">相关推荐</h3>
            <div class="related-grid">
              <div 
                v-for="news in relatedNews" 
                :key="news.id"
                class="related-item"
                @click="goToNews(news.id)"
              >
                <div class="related-image">
                  <img :src="news.coverImage || '/default-news.jpg'" :alt="news.title" />
                </div>
                <div class="related-content">
                  <h4 class="related-title">{{ news.title }}</h4>
                  <div class="related-meta">
                    <span>{{ news.viewCount }} 阅读</span>
                    <span>{{ formatTime(news.publishTime) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
        
        <!-- 加载失败 -->
        <div class="error-state" v-else-if="!loading">
          <el-empty description="新闻不存在或已被删除">
            <el-button type="primary" @click="goHome">返回首页</el-button>
          </el-empty>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getNewsDetail, getNewsList, likeNews } from '@/api/news'
import { View, Star, StarFilled, Share } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const newsDetail = ref(null)
const relatedNews = ref([])
const liked = ref(false)
const liking = ref(false)

// 方法
const fetchNewsDetail = async () => {
  loading.value = true
  try {
    const id = route.params.id
    newsDetail.value = await getNewsDetail(id)
    
    // 获取相关新闻
    if (newsDetail.value.categoryId) {
      await fetchRelatedNews()
    }
  } catch (error) {
    console.error('获取新闻详情失败:', error)
    ElMessage.error('获取新闻详情失败')
  } finally {
    loading.value = false
  }
}

const fetchRelatedNews = async () => {
  try {
    const data = await getNewsList({
      categoryId: newsDetail.value.categoryId,
      size: 6
    })
    
    // 排除当前新闻
    relatedNews.value = (data.results || []).filter(
      news => news.id !== parseInt(route.params.id)
    ).slice(0, 4)
  } catch (error) {
    console.error('获取相关新闻失败:', error)
  }
}

const handleLike = async () => {
  if (liking.value) return
  
  liking.value = true
  try {
    await likeNews(newsDetail.value.id)
    newsDetail.value.likeCount += 1
    liked.value = true
    ElMessage.success('点赞成功')
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('点赞失败')
  } finally {
    liking.value = false
  }
}

const handleShare = () => {
  if (navigator.share) {
    navigator.share({
      title: newsDetail.value.title,
      text: newsDetail.value.summary,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href).then(() => {
      ElMessage.success('链接已复制到剪贴板')
    }).catch(() => {
      ElMessage.error('复制失败')
    })
  }
}

const goHome = () => {
  router.push('/')
}

const goBack = () => {
  router.go(-1)
}

const goToNews = (id) => {
  router.push({ name: 'NewsDetail', params: { id } })
  // 重新加载当前新闻
  nextTick(() => {
    fetchNewsDetail()
  })
}

const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchNewsDetail()
})
</script>

<style scoped>
.news-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.header {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.logo {
  cursor: pointer;
}

.logo h1 {
  color: #409eff;
  font-size: 20px;
  margin: 0;
}

/* 主要内容 */
.main {
  padding: 30px 0;
}

.article {
  background: white;
  border-radius: 8px;
  padding: 40px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

.article-header {
  margin-bottom: 30px;
}

.article-title {
  font-size: 32px;
  color: #303133;
  line-height: 1.4;
  margin: 0 0 20px 0;
  font-weight: 600;
}

.article-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  color: #909399;
  font-size: 14px;
}

.meta-left {
  display: flex;
  gap: 20px;
}

.meta-right {
  display: flex;
  gap: 20px;
}

.meta-right span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.category {
  background: #409eff;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.article-cover {
  margin: 30px 0;
  text-align: center;
}

.article-cover img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.article-summary {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin: 30px 0;
  border-left: 4px solid #409eff;
}

.article-summary p {
  color: #606266;
  font-size: 16px;
  line-height: 1.6;
  margin: 0;
  font-style: italic;
}

.article-content {
  font-size: 16px;
  line-height: 1.8;
  color: #303133;
  margin: 30px 0;
}

.article-content :deep(p) {
  margin: 0 0 16px 0;
}

.article-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 16px 0;
}

.article-content :deep(h1),
.article-content :deep(h2),
.article-content :deep(h3) {
  margin: 24px 0 16px 0;
  color: #303133;
}

.article-footer {
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px solid #ebeef5;
}

.article-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

/* 相关推荐 */
.related-news {
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.section-title {
  font-size: 20px;
  color: #303133;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.related-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.related-item:hover {
  background-color: #f5f7fa;
}

.related-image {
  width: 80px;
  height: 60px;
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
}

.related-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.related-content {
  flex: 1;
}

.related-title {
  font-size: 14px;
  color: #303133;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.related-meta {
  display: flex;
  gap: 15px;
  color: #909399;
  font-size: 12px;
}

/* 错误状态 */
.error-state {
  background: white;
  border-radius: 8px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .article {
    padding: 20px;
  }
  
  .article-title {
    font-size: 24px;
  }
  
  .article-meta {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .related-grid {
    grid-template-columns: 1fr;
  }
  
  .related-item {
    padding: 10px;
  }
}
</style>
